﻿/******************************************************************************
 *  作者：       scott
 *  创建时间：   2012/3/8 20:58:11
 *
 *
 ******************************************************************************/

using System.Collections.Generic;
using AutoMapper;
using EasyMvcBlog.DTO;
using EasyMvcBlog.Data;
using EasyMvcBlog.Infrastructure.Repository;
using EasyMvcBlog.Infrastructure.Repository.DataRepository;

namespace EasyMvcBlog.Domain
{
    public class CategoryDomain
    {
        private RepositoryBase<Category> categoryRepository = new RepositoryBase<Category>();

        public List<CategoryDTO> AllCategory
        {
            get
            {
                List<Category> categories = categoryRepository.GetAll();

                Mapper.CreateMap<Category, CategoryDTO>();
                return Mapper.Map<List<Category>, List<CategoryDTO>>(categories);
            }
        }

        public bool AddCategory(Category newCategory)
        {
            return categoryRepository.Add(newCategory).Id > 0;
        }

        public bool Update(int categoryId, string newName)
        {
            Category category = categoryRepository.GetById(categoryId);
            if (category.Id > 0)
            {
                category.CategoryName = newName;
                categoryRepository.Update(category);
                return true;
            }
            return false;
        }

        public bool Delete(int categoryId)
        {
            //首先修改这个目录下所有文章的目录为空
            ArticleDomain articleDomain = new ArticleDomain();
            List<ArticleDTO> artiles = articleDomain.GetArticleByCategory(categoryId);
            foreach (ArticleDTO article in artiles)
            {
                article.Category = null;
                articleDomain.UpdateArticle(article);
            }
            categoryRepository.DeleteById<Category>(categoryId);
            return categoryRepository.GetById(categoryId) == null;
        }
    }
}
